'use client';

import React, { useEffect, useState } from 'react';
import { Card, Button, Result, message, Modal, Space } from 'antd';
import { useSearchParams, useRouter } from 'next/navigation';
import { uploadOfferResult, OfferAcceptStatus } from '@/lib/onboarding';
import { motion } from 'framer-motion';
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';

const OfferAcceptPage = () => {
  const searchParams = useSearchParams();
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [showConfirmModal, setShowConfirmModal] = useState(false);
  const [selectedAction, setSelectedAction] = useState<OfferAcceptStatus | null>(null);
  const [showSuccess, setShowSuccess] = useState(false);

  // 处理 URL 中的 token
  useEffect(() => {
    const currentToken = searchParams.get('token');
    if (currentToken?.includes('%7B') || currentToken?.includes('%7D')) {
      const cleanToken = decodeURIComponent(currentToken)
        .replace(/^\{|\}$/g, '');
      window.location.href = `/recruitment/offer/accept/result?token=${cleanToken}`;
    }
  }, [searchParams]);

  // 获取 token
  const token = searchParams.get('token')?.replace(/^\{|\}$/g, '') || '';

  // 如果没有 token，显示 404
  if (!token) {
    return (
      <Result
        status="404"
        title="404"
        subTitle="对不起，您访问的页面不存在。"
      />
    );
  }

  // 处理 Offer 结果提交
  const handleSubmitResult = async () => {
    if (!selectedAction) return;

    try {
      setLoading(true);
      console.log('提交的 token:', token);
      
      const result = selectedAction === OfferAcceptStatus.Accept ? 1 : 2;
      console.log('提交的结果:', result);
      
      const response = await uploadOfferResult(token, result);

      if (response.code === 1) {
        setShowSuccess(true);
        setShowConfirmModal(false);
        setTimeout(() => {
          message.success(selectedAction === OfferAcceptStatus.Accept ? '您已接受 Offer' : '您已拒绝 Offer');
        }, 500);
      } else {
        message.error(response.data || response.msg || '操作失败');
      }
    } catch (error: any) {
      console.error('提交 Offer 结果失败:', error);
      message.error(error.response?.data?.data || error.response?.data?.msg || error.message || '操作失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  // 处理选择结果
  const handleSelectResult = (status: OfferAcceptStatus) => {
    setSelectedAction(status);
    setShowConfirmModal(true);
  };

  if (showSuccess) {
    return (
      <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }} className="bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center p-4">
        <motion.div
          initial={{ scale: 0.5, opacity: 0 }}
          animate={{ scale: 1, opacity: 1 }}
          transition={{ duration: 0.5 }}
          className="w-full max-w-lg"
        >
          <Result
            status="success"
            title={
              <motion.div
                initial={{ y: -20 }}
                animate={{ y: 0 }}
                transition={{ delay: 0.2 }}
                className="text-2xl font-bold text-white"
              >
                {selectedAction === OfferAcceptStatus.Accept ? "恭喜您！" : "感谢您的回复"}
              </motion.div>
            }
            subTitle={
              <motion.div
                initial={{ y: 20, opacity: 0 }}
                animate={{ y: 0, opacity: 1 }}
                transition={{ delay: 0.4 }}
                className="text-lg text-white mt-4"
              >
                {selectedAction === OfferAcceptStatus.Accept
                  ? "您已成功接受 Offer，我们期待您的加入！"
                  : "您已拒绝 Offer，祝您前程似锦！"
                }
              </motion.div>
            }
            className="bg-white/90 backdrop-blur-sm shadow-2xl rounded-2xl p-8"
          />
        </motion.div>
      </div>
    );
  }

  return (
    <div style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }} className="bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 flex items-center justify-center p-4 relative">
      {/* 背景装饰 */}
      <div className="absolute inset-0 overflow-hidden">
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 0.5 }}
          transition={{ duration: 1 }}
          className="absolute top-0 left-0 w-[200%] h-[200%] bg-gradient-to-br from-blue-200/20 to-transparent rounded-full blur-3xl transform -translate-x-1/4 -translate-y-1/4"
        />
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 0.5 }}
          transition={{ duration: 1, delay: 0.2 }}
          className="absolute bottom-0 right-0 w-[200%] h-[200%] bg-gradient-to-tl from-purple-200/20 to-transparent rounded-full blur-3xl transform translate-x-1/4 translate-y-1/4"
        />
      </div>

      {/* 主要内容 */}
      <motion.div
        initial={{ y: 20, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.5 }}
        className="w-full max-w-xl md:max-w-2xl relative z-10 px-4 md:px-0"
      >
        <Card 
          title={
            <motion.div
              initial={{ y: -20, opacity: 0 }}
              animate={{ y: 0, opacity: 1 }}
              transition={{ delay: 0.2 }}
              className="text-center text-2xl md:text-3xl font-bold text-gray-800"
            >
              Offer 接受确认
            </motion.div>
          }
          className="shadow-2xl rounded-2xl md:rounded-3xl overflow-hidden backdrop-blur-sm bg-white/90 border-0"
          headStyle={{ 
            borderBottom: '2px solid rgba(240, 240, 240, 0.5)',
            padding: '24px 16px',
            backgroundColor: 'rgba(255, 255, 255, 0.7)'
          }}
          bodyStyle={{
            padding: '32px 20px'
          }}
        >
          <motion.div 
            className="text-center space-y-8 md:space-y-12"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ delay: 0.3 }}
          >
            <p className="text-gray-600 text-xl md:text-2xl font-medium">
              请确认是否接受本次 Offer
            </p>
            
            <Space size="middle" className="flex flex-col md:flex-row justify-center items-center gap-4 md:gap-8">
              <motion.div 
                whileHover={{ scale: 1.05 }} 
                whileTap={{ scale: 0.95 }}
                className="shadow-lg hover:shadow-2xl transition-shadow duration-300 w-full md:w-auto"
              >
                <Button
                  type="primary"
                  size="large"
                  onClick={() => handleSelectResult(OfferAcceptStatus.Accept)}
                  icon={<CheckCircleOutlined />}
                  style={{ 
                    width: '100%',
                    minWidth: '200px',
                    maxWidth: '240px',
                    height: '56px',
                    backgroundColor: '#52c41a',
                    borderColor: '#52c41a',
                    fontSize: '18px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px'
                  }}
                  loading={loading}
                  className="hover:opacity-90 transition-opacity duration-300"
                >
                  接受 Offer
                </Button>
              </motion.div>
              
              <motion.div 
                whileHover={{ scale: 1.05 }} 
                whileTap={{ scale: 0.95 }}
                className="shadow-lg hover:shadow-2xl transition-shadow duration-300 w-full md:w-auto"
              >
                <Button
                  danger
                  size="large"
                  onClick={() => handleSelectResult(OfferAcceptStatus.Reject)}
                  icon={<CloseCircleOutlined />}
                  style={{ 
                    width: '100%',
                    minWidth: '200px',
                    maxWidth: '240px',
                    height: '56px',
                    fontSize: '18px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: '8px'
                  }}
                  loading={loading}
                  className="hover:opacity-90 transition-opacity duration-300"
                >
                  拒绝 Offer
                </Button>
              </motion.div>
            </Space>

            <motion.p 
              className="text-gray-400 text-sm md:text-base mt-8 md:mt-12"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.4 }}
            >
              注意：此操作不可撤销，请谨慎选择
            </motion.p>
          </motion.div>
        </Card>
      </motion.div>

      {/* 确认弹窗 */}
      <Modal
        title={
          <div className="text-2xl font-bold text-center py-2">
            {selectedAction === OfferAcceptStatus.Accept ? '接受确认' : '拒绝确认'}
          </div>
        }
        open={showConfirmModal}
        onCancel={() => !loading && setShowConfirmModal(false)}
        onOk={handleSubmitResult}
        okText="确认"
        cancelText="取消"
        confirmLoading={loading}
        centered
        maskClosable={!loading}
        className="rounded-2xl overflow-hidden"
        width={480}
        bodyStyle={{ padding: '32px 24px' }}
      >
        <div className="py-6 text-center">
          <p className="text-xl text-gray-700 mb-6">
            {selectedAction === OfferAcceptStatus.Accept 
              ? '您确定要接受这份 Offer 吗？' 
              : '您确定要拒绝这份 Offer 吗？'
            }
          </p>
          <p className="text-gray-400 text-base">
            注意：此操作一旦确认将无法更改
          </p>
        </div>
      </Modal>
    </div>
  );
};

export default OfferAcceptPage; 